import { clearAuthCache, getAuthToken, setAuthToken } from '@/utils/cache'
import axios from 'axios'
import { defineStore } from 'pinia'
import { useMenuStore } from './menu'

interface UserInfo {
  id: number
  username: string
  email: string
  role: string
  is_staff: boolean
  is_superuser: boolean
  avatar_url?: string
  avatar?: string
  chinese_name?: string
}

interface AppState {
  token: string | null
  userInfo: UserInfo | null
  sidebar: {
    opened: boolean
    withoutAnimation: boolean
  }
  hosts: any[]
  users: any[]
  connections: any[]
  permissions: Record<string, boolean>
}

export const useAppStore = defineStore('app', {
  state: (): AppState => ({
    token: getAuthToken(),
    userInfo: null,
    sidebar: {
      opened: true,
      withoutAnimation: false
    },
    hosts: [],
    users: [],
    connections: [],
    permissions: {}
  }),

  getters: {
    isAuthenticated: (state) => !!state.token,
    name: (state) => state.userInfo?.username || '',
    role: (state) => state.userInfo?.role || '',
    avatar: (state) => {
      const avatarUrl = state.userInfo?.avatar_url || state.userInfo?.avatar
      if (avatarUrl && avatarUrl !== 'null' && avatarUrl !== null) {
        // 获取后端地址
        const globalConfig = (window as any).DEVOPS_CONFIG
        let backendUrl = globalConfig?.API_BASE_URL

        // 如果配置文件中没有设置，使用自动检测
        if (!backendUrl || !backendUrl.trim()) {
          const hostname = window.location.hostname
          const protocol = window.location.protocol
          backendUrl = `${protocol}//${hostname}:8000`
        }

        // 如果是相对路径，添加后端地址前缀
        if (avatarUrl.startsWith('/')) {
          return backendUrl + avatarUrl
        }
        // 如果已经是完整URL，直接返回
        return avatarUrl
      }
      return null
    }
  },

  actions: {
    // 登录
    async login(credentials: { username: string; password: string }) {
      try {
        console.log('🔑 开始登录，清理旧缓存...')

        // 先清理旧的缓存数据
        clearAuthCache()

        const response = await axios.post('/api/token/', credentials)
        const token = response.data.token

        console.log('✅ 登录成功，设置新token')

        // 使用安全的token设置方法
        if (setAuthToken(token)) {
          this.token = token

          await this.getUserInfo()

          // 使用新菜单系统
          const menuStore = useMenuStore()
          await menuStore.loadUserMenus()

          console.log('✅ 用户信息加载完成:', this.userInfo?.username)
          return response.data
        } else {
          throw new Error('无效的token格式')
        }
      } catch (error) {
        console.error('❌ 登录失败:', error)
        // 登录失败时也要清理缓存
        await this.logout()
        throw error
      }
    },

    // 注册
    async register(userData: any) {
      try {
        const response = await axios.post('/api/register/', userData)
        return response.data
      } catch (error) {
        console.error('注册失败:', error)
        throw error
      }
    },

    // 获取用户信息
    async getUserInfo(forceRefresh = false) {
      try {
        const url = forceRefresh
          ? `/api/users/current/?t=${Date.now()}`
          : '/api/users/current/'
        const response = await axios.get(url)
        this.userInfo = response.data
        console.log('用户信息已更新:', this.userInfo)
        return response.data
      } catch (error) {
        console.error('获取用户信息失败:', error)
        await this.logout()
        throw error
      }
    },

    // 登出
    async logout() {
      console.log('🚪 开始退出登录，清理所有缓存...')

      // 使用统一的缓存清理工具
      clearAuthCache()

      // 清理 store 状态
      this.token = null
      this.userInfo = null
      this.permissions = {}
      this.hosts = []
      this.users = []
      this.connections = []

      // 清理菜单store
      const menuStore = useMenuStore()
      menuStore.clearMenus()

      console.log('✅ 退出登录完成')

      // 跳转到登录页面（使用window.location避免循环依赖）
      if (window.location.pathname !== '/login') {
        window.location.href = '/login'
      }
    },

    // 检查路径权限（使用新菜单系统）
    async checkPathPermission(path: string): Promise<boolean> {
      try {
        const menuStore = useMenuStore()
        const hasPermission = menuStore.checkPathPermission(path)
        this.permissions[path] = hasPermission
        return hasPermission
      } catch (error) {
        console.error('权限检查失败:', error)
        return false
      }
    },

    // 切换侧边栏
    toggleSidebar() {
      this.sidebar.opened = !this.sidebar.opened
      this.sidebar.withoutAnimation = false
    },

    // 关闭侧边栏
    closeSidebar(withoutAnimation: boolean = false) {
      this.sidebar.opened = false
      this.sidebar.withoutAnimation = withoutAnimation
    },

    // 获取主机列表
    async getHosts() {
      try {
        const response = await axios.get('/api/hosts/')
        this.hosts = response.data.results || response.data
        return this.hosts
      } catch (error) {
        console.error('获取主机列表失败:', error)
        throw error
      }
    },

    // 创建主机
    async createHost(hostData: any) {
      try {
        const response = await axios.post('/api/hosts/', hostData)
        return response.data
      } catch (error) {
        console.error('创建主机失败:', error)
        throw error
      }
    },

    // 更新主机
    async updateHost(hostId: number, hostData: any) {
      try {
        const response = await axios.put(`/api/hosts/${hostId}/`, hostData)
        return response.data
      } catch (error) {
        console.error('更新主机失败:', error)
        throw error
      }
    },

    // 删除主机
    async deleteHost(hostId: number) {
      try {
        await axios.delete(`/api/hosts/${hostId}/`)
        return true
      } catch (error) {
        console.error('删除主机失败:', error)
        throw error
      }
    },

    // 刷新单个主机信息
    async refreshHostInfo(hostId: number) {
      try {
        const response = await axios.post(`/api/hosts/${hostId}/refresh/`)

        if (response.data.success) {
          // 更新本地主机信息
          const index = this.hosts.findIndex(host => host.id === hostId)
          if (index !== -1) {
            this.hosts[index] = response.data.data
          }
          return { success: true, data: response.data }
        } else {
          return { success: false, message: response.data.message }
        }
      } catch (error: any) {
        console.error('刷新主机信息失败:', error)
        const message = error.response?.data?.message || '刷新主机信息失败'
        return { success: false, message }
      }
    },

    // 刷新所有主机信息
    async refreshAllHosts() {
      try {
        const response = await axios.post('/api/hosts/refresh-all/')

        if (response.data.success) {
          // 重新获取主机列表
          await this.getHosts()
          return {
            success: true,
            message: response.data.message || '刷新在线主机信息成功'
          }
        } else {
          return {
            success: false,
            message: response.data.message || '刷新在线主机信息失败'
          }
        }
      } catch (error: any) {
        console.error('刷新在线主机信息失败:', error)
        const message = error.response?.data?.message || '刷新在线主机信息失败'
        return { success: false, message }
      }
    },

    // 批量刷新主机信息
    async batchRefreshHosts(hostIds: number[]) {
      try {
        const response = await axios.post('/api/hosts/batch-refresh/', {
          host_ids: hostIds
        })

        if (response.data.success) {
          // 重新获取主机列表
          await this.getHosts()
          return { success: true, data: response.data }
        } else {
          return { success: false, message: response.data.message }
        }
      } catch (error: any) {
        console.error('批量刷新主机信息失败:', error)
        const message = error.response?.data?.message || '批量刷新主机信息失败'
        return { success: false, message }
      }
    },

    // 获取用户列表
    async getUsers() {
      try {
        const response = await axios.get('/api/users/')
        this.users = response.data.results || response.data
        return this.users
      } catch (error) {
        console.error('获取用户列表失败:', error)
        throw error
      }
    },

    // 获取连接记录
    async getConnections() {
      try {
        const response = await axios.get('/api/connections/')
        this.connections = response.data.results || response.data
        return this.connections
      } catch (error) {
        console.error('获取连接记录失败:', error)
        throw error
      }
    },

    // 获取主机类型列表
    async getHostTypes() {
      try {
        const response = await axios.get('/api/hosttypes/')
        return response.data
      } catch (error) {
        console.error('获取主机类型失败:', error)
        throw error
      }
    }
  }
})
